package com.openvalley.cyj.examination.slice;

import com.openvalley.cyj.examination.DataUserAbility;
import com.openvalley.cyj.examination.ResourceTable;
import com.openvalley.cyj.examination.constant.ConstantOfTableUser;
import com.openvalley.cyj.examination.pojo.User;
import com.openvalley.cyj.examination.save.PageData;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.IDataAbilityObserver;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.data.dataability.DataAbilityPredicates;
import ohos.data.rdb.ValuesBucket;
import ohos.data.resultset.ResultSet;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainAbilitySlice extends AbilitySlice {
    private static final HiLogLabel LABEL_LOG = new HiLogLabel(HiLog.LOG_APP, 0x000001, MainAbilitySlice.class.getSimpleName());

    DataAbilityHelper dataAbilityHelper = null;

    Checkbox mainCheckBoxReadAgreement = null;
    Button mainBtnLogin = null;
    TextField mainTextFieldLoginName = null;
    Text mainTextLoginNameErrorTip = null;
    TextField mainTextFieldPassword = null;
    Text mainTextPasswordErrorTip = null;

    ShapeElement mainTextFieldLoginErrorBackground = null;
    ShapeElement mainTextFieldLoginBackground = null;

    //获取media资源
    Resource mainMediaWinterResource = null;
    PixelMapElement mainMediaWinterElement = null;
    Resource mainMediaWinterBWResource = null;
    PixelMapElement mainMediaWinterBWElement = null;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        //判断用户是否是已经登录了的
        checkIsLogin();

        //初始化组件等
        initComponent();

        //因为创建表时没有数据，所以就手动加
        addUserData();

        //初始化观察者
        initObserver();

        //初始化监听
        initListen();
    }

    private void checkIsLogin(){
        User user = PageData.getInstance().getUser();
        if(user != null && user.getUser_is_login() == 1){
            //如果页面全局数据中存放了user且存放的user登录状态是1，证明用户已经登录，此时应该直接进入detail页面
            toDetailPage();
        }
    }

    /**
     * 添加user表的默认数据，每次开启程序默认先进入此页面，所以这个方法每次都会调用一次
     */
    private void addUserData(){
        //先查询是否已经添加过该默认数据了
        DataAbilityPredicates predicates = new DataAbilityPredicates();
        predicates.equalTo(ConstantOfTableUser.DATABASE_COLUMN_NAME, "selma");

        if(null == doQueryOfTableUser(predicates)){
            //身份 0 管理员
            //权限 0 畅通无阻
            //isLogin 0 未登录
            User adminUser = new User(1, "selma", "123456", 0, 0, 0);
            doInsertOfTableUser(adminUser);
        }
    }

    /**
     * user表添加字段
     * @param user
     */
    private void doInsertOfTableUser(User user) {
        try{
            ValuesBucket valuesBucket = new ValuesBucket();
            valuesBucket.putString(ConstantOfTableUser.DATABASE_COLUMN_NAME, user.getUser_name());
            valuesBucket.putString(ConstantOfTableUser.DATABASE_COLUMN_PASSWORD, user.getUser_password());
            valuesBucket.putInteger(ConstantOfTableUser.DATABASE_COLUMN_IDENTITY, user.getUser_identity());
            valuesBucket.putInteger(ConstantOfTableUser.DATABASE_COLUMN_AUTHORITY, user.getUser_authority());
            valuesBucket.putInteger(ConstantOfTableUser.DATABASE_COLUMN_IS_LOGIN, user.getUser_is_login());

            int resultRow = dataAbilityHelper.insert(Uri.parse(ConstantOfTableUser.DATABASE_URI + ConstantOfTableUser.DATABASE_TABLE_NAME_PATH), valuesBucket);
            HiLog.info(LABEL_LOG, "doInsertOfTableUser 数据插入成功 resultRow = " + resultRow);
        }catch (Exception e){
            HiLog.info(LABEL_LOG, "doInsertOfTableUser 数据插入失败 result = " + e.getMessage());
        }
    }

    /**
     * user表更新字段，你只要让它更新不管数据变没变它不失败resultRow都有个值（多少忘了
     * @param user
     * @param predicates
     * @return
     */
    private boolean doUpdateOfTableUser(User user, DataAbilityPredicates predicates){
        boolean flag = false;
        try{
            ValuesBucket valuesBucket = new ValuesBucket();
            valuesBucket.putString(ConstantOfTableUser.DATABASE_COLUMN_NAME, user.getUser_name());
            valuesBucket.putString(ConstantOfTableUser.DATABASE_COLUMN_PASSWORD, user.getUser_password());
            valuesBucket.putInteger(ConstantOfTableUser.DATABASE_COLUMN_IDENTITY, user.getUser_identity());
            valuesBucket.putInteger(ConstantOfTableUser.DATABASE_COLUMN_AUTHORITY, user.getUser_authority());
            valuesBucket.putInteger(ConstantOfTableUser.DATABASE_COLUMN_IS_LOGIN, user.getUser_is_login());

//            DataAbilityPredicates predicates = new DataAbilityPredicates();
//            predicates.equalTo(ConstantOfTableUser.DATABASE_COLUMN_ID, 1);

            int resultRow = dataAbilityHelper.update(Uri.parse(ConstantOfTableUser.DATABASE_URI + ConstantOfTableUser.DATABASE_TABLE_NAME_PATH), valuesBucket, predicates);
            flag = true;
            HiLog.info(LABEL_LOG, "MainAbilitySlice doUpdate 修改成功。 resultRow = " + resultRow);
        }catch (Exception e){
            HiLog.info(LABEL_LOG, "MainAbilitySlice doUpdate 修改失败。 result = " + e.getMessage());
        }
        return flag;
    }

    /**
     * user表查询所有
     */
    private List<User> doQueryAllOfTableUser(){
        List<User> queryUserList = null;
        try{
            String[] columns = {
                    ConstantOfTableUser.DATABASE_COLUMN_ID,
                    ConstantOfTableUser.DATABASE_COLUMN_NAME,
                    ConstantOfTableUser.DATABASE_COLUMN_PASSWORD,
                    ConstantOfTableUser.DATABASE_COLUMN_IDENTITY,
                    ConstantOfTableUser.DATABASE_COLUMN_AUTHORITY,
                    ConstantOfTableUser.DATABASE_COLUMN_IS_LOGIN
            };
            DataAbilityPredicates predicates = new DataAbilityPredicates();
            //不给条件就是查询全部

            ResultSet resultSet = dataAbilityHelper.query(Uri.parse(ConstantOfTableUser.DATABASE_URI + ConstantOfTableUser.DATABASE_TABLE_NAME_PATH), columns, predicates);
            if(!resultSet.goToFirstRow()){
                HiLog.info(LABEL_LOG, "doQueryAllOfTableUser 未查到数据。");
            }else {
                //如果查到数据了
                queryUserList = new ArrayList<>();
                do{
                    int userId = resultSet.getInt(resultSet.getColumnIndexForName(ConstantOfTableUser.DATABASE_COLUMN_ID));
                    String userName = resultSet.getString(resultSet.getColumnIndexForName(ConstantOfTableUser.DATABASE_COLUMN_NAME));
                    String userPassword = resultSet.getString(resultSet.getColumnIndexForName(ConstantOfTableUser.DATABASE_COLUMN_PASSWORD));
                    int userIdentity = resultSet.getInt(resultSet.getColumnIndexForName(ConstantOfTableUser.DATABASE_COLUMN_IDENTITY));
                    int userAuthority = resultSet.getInt(resultSet.getColumnIndexForName(ConstantOfTableUser.DATABASE_COLUMN_AUTHORITY));
                    int userIsLogin = resultSet.getInt(resultSet.getColumnIndexForName(ConstantOfTableUser.DATABASE_COLUMN_IS_LOGIN));
                    User user = new User();
                    user.setUser_id(userId);
                    user.setUser_name(userName);
                    user.setUser_password(userPassword);
                    user.setUser_identity(userIdentity);
                    user.setUser_authority(userAuthority);
                    user.setUser_is_login(userIsLogin);
                    queryUserList.add(user);
                    HiLog.info(LABEL_LOG, "doQueryAllOfTableUser userId = " + userId + " user_name = " + userName + " user_password = " + userPassword);
                }while(resultSet.goToNextRow());
                resultSet.close();
            }
        }catch (Exception e){
            HiLog.info(LABEL_LOG, "doQueryAllOfTableUser 数据查询失败。 result = " + e.getMessage());
        }
        return queryUserList;
    }

    /**
     * user表查询部分字段
     * @param predicates
     * @return List<User>
     */
    private List<User> doQueryOfTableUser(DataAbilityPredicates predicates){
        List<User> queryUserList = null;
        try{
            String[] columns = {
                    ConstantOfTableUser.DATABASE_COLUMN_ID,
                    ConstantOfTableUser.DATABASE_COLUMN_NAME,
                    ConstantOfTableUser.DATABASE_COLUMN_PASSWORD,
                    ConstantOfTableUser.DATABASE_COLUMN_IDENTITY,
                    ConstantOfTableUser.DATABASE_COLUMN_AUTHORITY,
                    ConstantOfTableUser.DATABASE_COLUMN_IS_LOGIN
            };
            ResultSet resultSet = dataAbilityHelper.query(Uri.parse(ConstantOfTableUser.DATABASE_URI + ConstantOfTableUser.DATABASE_TABLE_NAME_PATH), columns, predicates);
            if(!resultSet.goToFirstRow()){
                //如果未查到数据
                HiLog.info(LABEL_LOG, "doQueryOfTableUser 未查到数据。");
            }else {
                //如果查到数据了
                queryUserList = new ArrayList<>();
                do{
                    int userId = resultSet.getInt(resultSet.getColumnIndexForName(ConstantOfTableUser.DATABASE_COLUMN_ID));
                    String userName = resultSet.getString(resultSet.getColumnIndexForName(ConstantOfTableUser.DATABASE_COLUMN_NAME));
                    String userPassword = resultSet.getString(resultSet.getColumnIndexForName(ConstantOfTableUser.DATABASE_COLUMN_PASSWORD));
                    int userIdentity = resultSet.getInt(resultSet.getColumnIndexForName(ConstantOfTableUser.DATABASE_COLUMN_IDENTITY));
                    int userAuthority = resultSet.getInt(resultSet.getColumnIndexForName(ConstantOfTableUser.DATABASE_COLUMN_AUTHORITY));
                    int userIsLogin = resultSet.getInt(resultSet.getColumnIndexForName(ConstantOfTableUser.DATABASE_COLUMN_IS_LOGIN));
                    User user = new User();
                    user.setUser_id(userId);
                    user.setUser_name(userName);
                    user.setUser_password(userPassword);
                    user.setUser_identity(userIdentity);
                    user.setUser_authority(userAuthority);
                    user.setUser_authority(userAuthority);
                    user.setUser_is_login(userIsLogin);
                    queryUserList.add(user);
                    HiLog.info(LABEL_LOG, "doQueryOfTableUser userId = " + userId + " user_name = " + userName + " user_password = " + userPassword);
                }while(resultSet.goToNextRow());
                resultSet.close();
            }
        }catch (Exception e){
            HiLog.info(LABEL_LOG, "doQueryOfTableUser 数据查询失败。 result = " + e.getMessage());
        }
        return queryUserList;
    }

    /**
     * 初始化各个用到的页面上的组件（可能还有其他的东西，包括但不限于组件）
     */
    private void initComponent(){
        //数据能力帮助类
        dataAbilityHelper = DataAbilityHelper.creator(getContext());

        //首页的 是否阅读了协议的 多选框
        mainCheckBoxReadAgreement = (Checkbox)findComponentById(ResourceTable.Id_main_check_box_read_agreement);
        //首页的 登录 按钮
        mainBtnLogin = (Button) findComponentById(ResourceTable.Id_main_login_btn);
        //首页的 输入登录名的 文字域
        mainTextFieldLoginName = (TextField) findComponentById(ResourceTable.Id_main_text_field_login_name);
        //首页的 登录名输入错误时 展示的警示外框 Text
        mainTextLoginNameErrorTip = (Text) findComponentById(ResourceTable.Id_main_text_login_name_error_tip);
        //首页的 输入密码的 文字域
        mainTextFieldPassword = (TextField) findComponentById(ResourceTable.Id_main_text_field_password);
        //首页的 密码输入错误时 展示的警示外框 Text
        mainTextPasswordErrorTip = (Text) findComponentById(ResourceTable.Id_main_text_password_error_tip);
        //首页的 登录名或密码输入错误时 展示的警示外框的形状文件
        mainTextFieldLoginErrorBackground = new ShapeElement(this, ResourceTable.Graphic_main_text_field_login_error_background);
        //首页的 登录名或密码输入错误时 展示的警示外框的形状文件
        mainTextFieldLoginBackground = new ShapeElement(this, ResourceTable.Graphic_main_text_field_login_background);

        //图片有关的资源
        try {
            mainMediaWinterResource = getResourceManager().getResource(ResourceTable.Media_main_login_winter);
            mainMediaWinterBWResource = getResourceManager().getResource(ResourceTable.Media_main_login_winter_bw);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        }
        mainMediaWinterElement = new PixelMapElement(mainMediaWinterResource);
        mainMediaWinterBWElement = new PixelMapElement(mainMediaWinterBWResource);
    }

    /**
     * 注册观察者
     */
    private void initObserver(){
        //注册观察者
        dataAbilityHelper.registerObserver(Uri.parse(ConstantOfTableUser.DATABASE_URI + ConstantOfTableUser.DATABASE_TABLE_NAME_PATH), new IDataAbilityObserver() {
            @Override
            public void onChange() {
                //当发生改变时做的事（此处是直接查询一次
                List<User> userList = doQueryAllOfTableUser();
                for (User user : userList) {
                    HiLog.info(LABEL_LOG, user.toString());
                }
            }
        });
    }

    /**
     * 初始化各个监听
     */
    private void initListen(){
        //同意服务协议多选框的监听
        mainCheckBoxReadAgreement.setCheckedStateChangedListener((listen, state) -> {
            if (state) {
                mainBtnLogin.setEnabled(true);
                mainBtnLogin.setBackground(mainMediaWinterElement);
            } else {
                mainBtnLogin.setEnabled(false);
                mainBtnLogin.setBackground(mainMediaWinterBWElement);
            }
        });

        //登录按钮的监听（在此处判断账号密码是否正确，不正确的部分要弹警示
        mainBtnLogin.setClickedListener(listen -> {
            //接收user，因为存在的话是需要更改登录状态的。
            User user = null;
            //获得页面上用户输入的内容
            String mainTextFieldLoginNameContent = mainTextFieldLoginName.getText();
            String mainTextFieldPasswordContent = mainTextFieldPassword.getText();
            //给定数据库的用户名和密码
            String dataUserLoginName = "selma";
            String dataUserPassword = "123456";
            //根据用户名和密码查询是否存在该用户
            DataAbilityPredicates predicatesToQuery = new DataAbilityPredicates();
            predicatesToQuery.equalTo(ConstantOfTableUser.DATABASE_COLUMN_NAME, mainTextFieldLoginNameContent);
            predicatesToQuery.equalTo(ConstantOfTableUser.DATABASE_COLUMN_PASSWORD, mainTextFieldPasswordContent);

            List<User> userList = doQueryOfTableUser(predicatesToQuery);
            if(userList != null){
                user = userList.get(0);
                dataUserLoginName = user.getUser_name();
                dataUserPassword = user.getUser_password();
            }
            if(!dataUserLoginName.equals(mainTextFieldLoginNameContent) || !dataUserPassword.equals(mainTextFieldPasswordContent)){
                //显示错误提示的Text
                mainTextLoginNameErrorTip.setVisibility(Component.VISIBLE);
                mainTextPasswordErrorTip.setVisibility(Component.VISIBLE);
                //显示TextField错误状态下的样式
                mainTextFieldLoginName.setBackground(mainTextFieldLoginErrorBackground);
                mainTextFieldPassword.setBackground(mainTextFieldLoginErrorBackground);
                //TextField失去焦点
                mainTextFieldLoginName.clearFocus();
                mainTextFieldPassword.clearFocus();
            }
            if(dataUserLoginName.equals(mainTextFieldLoginNameContent) && dataUserPassword.equals(mainTextFieldPasswordContent)){
                //如果账号密码都匹配，就跳转到判断题考试页（先把数据库里的当前用户的登录状态改变
                DataAbilityPredicates predicatesToUpdate = new DataAbilityPredicates();
                predicatesToUpdate.equalTo(ConstantOfTableUser.DATABASE_COLUMN_ID, user.getUser_id().intValue());
                user.setUser_is_login(1);
                doUpdateOfTableUser(user, predicatesToUpdate);
                //把页面数据存进app全局数据当中
                PageData.getInstance().setUser(user);
                toDetailPage();

                HiLog.info(LABEL_LOG, "登录成功。 username = " + dataUserLoginName + " password = " + dataUserPassword);
            }
        });

        //登录名输入框恢复原样监听（误
        mainTextFieldLoginName.setClickedListener(listen -> {
            mainTextFieldLoginName.setBackground(mainTextFieldLoginBackground);
            mainTextLoginNameErrorTip.setVisibility(Component.HIDE);
            mainTextFieldPassword.setBackground(mainTextFieldLoginBackground);
            mainTextPasswordErrorTip.setVisibility(Component.HIDE);
        });
        //登录名输入框添加监听事件，点击就恢复没错的状态（都恢复
        mainTextFieldPassword.setClickedListener(listen -> {
            mainTextFieldLoginName.setBackground(mainTextFieldLoginBackground);
            mainTextLoginNameErrorTip.setVisibility(Component.HIDE);
            mainTextFieldPassword.setBackground(mainTextFieldLoginBackground);
            mainTextPasswordErrorTip.setVisibility(Component.HIDE);
        });
    }

    /**
     * 跳转到detail页面并把当前页面销毁的方法
     */
    private void toDetailPage(){
        present(new DetailAbilitySlice(), new Intent());
        terminate();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
